<template>
    <van-nav-bar title="分类" />

    <van-tree-select 
        v-model:main-active-index="active" 
        height="100vh" 
        @click-nav="handleNavClick"  
        v-model="TypeActive" 
        :items="TypeList"
    >
        <template #content>
            <van-card 
                v-for="item in list" 
                :key="item.id"
                :price="item.price" 
                :title="item.name" 
                :thumb="item.thumb_text"
            >
                <template #num>
                    <van-button size="mini" @click="ProductInfo(item.id)">查看详情</van-button>
                </template>

                <!-- <template #desc>
                    <div v-html="item.content"></div>

                </template> -->
            </van-card>
        </template>
    </van-tree-select>
</template>

<script setup>

const { proxy } = getCurrentInstance()
const route = useRoute()

const active = ref(0)
const TypeActive = ref(route.query.typeid ?? 'all')
const TypeList = ref([{ text: '全部分类', value: 'all' }])
const list = ref([])

// 获取分类数据
const GetTypeData = async () => {
    const result = await proxy.$http.post('/product/type')
    if(result.code === 1) {
        TypeList.value = [
            { text: '全部分类', value: 'all' }, // 保留全部分类选项
            ...result.data.map(item => ({
                text: item.name,
                value: item.id
            }))
        ]
    }
}

// 点击分类导航时的处理
const handleNavClick = (index) => {
    // console.log(index);

    active.value = index
    TypeActive.value = TypeList.value[index].value
    loadProducts() // 统一使用这个函数加载商品
}

// 统一商品加载函数
const loadProducts = async () => {
    const params = {}
    
    // 只有当不是"全部分类"时才传typeid
    if(TypeActive.value !== 'all') {
        params.typeid = TypeActive.value
    }
    
    const result = await proxy.$http.post('/product/index', params)
    if(result.code === 1) {
        list.value = result.data.list || []
    }
}

// 查看商品详情
const ProductInfo = (proid) => {
    proxy.$router.push({
        path: '/product/info',
        query: { proid }
    })
}

// 初始化
onBeforeMount(() => {
    GetTypeData()
    loadProducts() // 使用统一的加载函数
})
</script>